﻿using System.Collections.Generic;

namespace Utils.Extensions
{
	public static class IEnumerableExtension
	{
		public static decimal FindBestSubsequence(this IEnumerable<decimal> source, out int startIndex, out int endIndex)
		{
			decimal result = decimal.MinValue;
			decimal sum = 0;
			int tempStart = 0;
			int index = 0;

			startIndex = 0;
			endIndex = 0;

			IEnumerator<decimal> sourceEnumerator = source.GetEnumerator();
			
			while (sourceEnumerator.MoveNext())
			{
				sum += sourceEnumerator.Current;
				if (sum > result)
				{
					result = sum;
					startIndex = tempStart;
					endIndex = index;
				}
				if (sum < 0)
				{
					sum = 0;
					tempStart = index + 1;
				}

				index++;
			}

			return result;
		}

		public static decimal FindWorstSubsequence(this IEnumerable<decimal> source, out int startIndex, out int endIndex)
		{
			List<decimal> tempList = new List<decimal>(source);

			for (int index = 0; index < tempList.Count; index++)
			{
				tempList[index] = tempList[index] * -1;
			}

			return FindBestSubsequence(tempList, out startIndex, out endIndex) * -1;
		}
	}
}
